﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using FikriKibar.Common.Helpers;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.DataAccess.ContextBase;
using FikriKibar.DataAccess.RepositoryBase;
using FikriKibar.Entities.Concrete;

namespace FikriKibar.DataAccess
{
    public class EfSessionHistoryDal : EfEntityRepositoryBase<SessionHistory, FikriKibarDbContext>, ISessionHistoryDal
    {
        protected override SessionHistory AddEntity(SessionHistory entity, FikriKibarDbContext context)
        {
            return context.SessionHistories.Add(entity);
        }

        protected override SessionHistory UpdateEntity(SessionHistory entity, FikriKibarDbContext context)
        {
            var oldEntity = GetEntity(entity, context);
            var newEntity = Mapper.Map(entity, oldEntity);
            context.Entry(oldEntity).CurrentValues.SetValues(newEntity);
            return newEntity;
        }

        protected override List<SessionHistory> GetEntities(FikriKibarDbContext context)
        {
            return context.SessionHistories.Include(e=>e.User).ToList();
        }

        protected override List<SessionHistory> FilterEntities(FikriKibarDbContext context, Expression<Func<SessionHistory, bool>> where)
        {
            return context.SessionHistories.Include(e=>e.User).Where(where).ToList();
        }
        protected override List<SessionHistory> FilterEntities(FikriKibarDbContext context, Expression<Func<SessionHistory, bool>> where, SortHelper<SessionHistory> sortHelper)
        {

            var query = (IOrderedQueryable<SessionHistory>) context.SessionHistories.Include(e=>e.User).Where(where);
            query = sortHelper.GenerateOrderedQuery(query);
            return query.ToList();
        }



        protected override List<SessionHistory> FilterEntities(FikriKibarDbContext context, Expression<Func<SessionHistory, bool>> where, SortHelper<SessionHistory> sortHelper, int index, int size)
        {
            var query = (IOrderedQueryable<SessionHistory>) context.SessionHistories.Include(e=>e.User).Where(where);
            query = sortHelper.GenerateOrderedQuery(query);
            return query.Skip((index - 1) * size).Take(size).ToList();
        }

        protected override SessionHistory GetEntity(SessionHistory entity, FikriKibarDbContext context)
        {
            return context.SessionHistories.Include(e=>e.User).FirstOrDefault(p => p.Id == entity.Id);
        }

    }
}
